package cn.blunce.TreeTest;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Experiment on 2016/3/25.
 */
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }

    TreeNode(String string) {
        String tree = string.substring(1, string.length() - 1);
        String[] nodes = tree.split(",");
        this.val = Integer.valueOf(nodes[0]);
        TreeNode point = this;
        Queue<String> node_queue = new LinkedList<String>();
        for (String node : nodes)
            node_queue.add(node);
        node_queue.remove();
        Queue<TreeNode> traverse_queue = new LinkedList<TreeNode>();
        traverse_queue.add(point);
        while (!traverse_queue.isEmpty()) {
            point = traverse_queue.remove();
            if (node_queue.isEmpty())
                break;
            else {
                String tmp = node_queue.remove();
                if (!tmp.equals("#")) {
                    point.left = new TreeNode(Integer.valueOf(tmp));
                    traverse_queue.add(point.left);
                }
            }
            if (node_queue.isEmpty())
                break;
            else {
                String tmp = node_queue.remove();
                if (!tmp.equals("#")) {
                    point.right = new TreeNode(Integer.valueOf(tmp));
                    traverse_queue.add(point.right);
                }
            }
        }
    }

    public String toString() {
        String tree = "";
        TreeNode point = this;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(point);
        while (!queue.isEmpty()) {
            point = queue.remove();
            tree += String.valueOf(point.val);
            tree += ",";
            if (point.left != null)
                queue.add(point.left);
            if (point.right != null)
                queue.add(point.right);
        }
        tree = tree.substring(0, tree.length() - 1);
        return "[" + tree + "]";
    }
}
